#
# fusion.sync.sync_daemon
#
# Copyright 2006-2007 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import time
from Queue import Queue, Empty

from fusion.db.sqlite_db import SqliteDB
from messkit.threaded_stream import StreamManager
from fusion.sync.sync_manager import SyncManager

class SyncDaemon(object):
    def __init__(self, path, host='', port=35800):
        self.path = path
        self.address = (host, port)

        self.db = None
        self.queue = Queue()
        self.queue.put(self._init)

    def _init(self):
        self.db = SqliteDB(self.path)
        self.stream_mgr = StreamManager(self.queue.put)
        self.sync_mgr = SyncManager(self.db, self.stream_mgr,
                                    listening_address = self.address)

    def loop(self, polling_interval=0.2):
        try:
            next_update = time.time() + polling_interval
            while True:
                try:
                    remaining = next_update - time.time()
                    if remaining > 0:
                        f = self.queue.get(timeout=remaining)
                        if not f:
                            break
                        f()
                    else:
                        self.sync_mgr.update()
                        next_update = time.time() + polling_interval
                except Empty:
                    pass
                except KeyboardInterrupt:
                    self._close()
        finally:
            if self.db is not None:
                self.db.close()

    def close(self):
        self.queue.put(self._close)

    def _close(self):
        self.stream_mgr.close(lambda: self.queue.put(None))

    def get_my_ip_addresses(self, types=('public',)):
        return self.sync_mgr.get_my_ip_addresses(types)
